package com.ruoyi.lh.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimerTask;
import java.util.stream.Collectors;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.lh.domain.Machine;
import com.ruoyi.lh.domain.User;
import com.ruoyi.lh.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lh.mapper.SoftwareMapper;
import com.ruoyi.lh.domain.Software;
import com.ruoyi.lh.service.ISoftwareService;
import com.ruoyi.common.core.text.Convert;

/**
 * 软件Service业务层处理
 *
 * @author LH
 * @date 2023-08-02
 */
@Service
public class SoftwareServiceImpl implements ISoftwareService {
  @Autowired private SoftwareMapper softwareMapper;

  @Autowired private IUserService userService;

  /**
   * 查询软件
   *
   * @param id 软件主键
   * @return 软件
   */
  @Override
  public Software selectSoftwareById(Long id) {
    return softwareMapper.selectSoftwareById(id);
  }

  /**
   * 查询软件列表
   *
   * @param software 软件
   * @return 软件
   */
  @Override
  public List<Software> selectSoftwareList(Software software) {
    return softwareMapper.selectSoftwareList(software);
  }

  /**
   * 新增软件
   *
   * @param software 软件
   * @return 结果
   */
  @Override
  public int insertSoftware(Software software) {
    return softwareMapper.insertSoftware(software);
  }

  /**
   * 修改软件
   *
   * @param software 软件
   * @return 结果
   */
  @Override
  public int updateSoftware(Software software) {
    return softwareMapper.updateSoftware(software);
  }

  /**
   * 批量删除软件
   *
   * @param ids 需要删除的软件主键
   * @return 结果
   */
  @Override
  public int deleteSoftwareByIds(String ids) {
    return softwareMapper.deleteSoftwareByIds(Convert.toStrArray(ids));
  }

  /**
   * 删除软件信息
   *
   * @param id 软件主键
   * @return 结果
   */
  @Override
  public int deleteSoftwareById(Long id) {
    return softwareMapper.deleteSoftwareById(id);
  }

  /**
   * @param excludeSN 排除的设备
   * @return
   */
  @Override
  public List<Machine> selectMachineList(String excludeSN) {
    List<String> snList = new ArrayList<>();
    if (StringUtils.isNotEmpty(excludeSN)) {
      snList = Arrays.asList(excludeSN.split(","));
    }
    return softwareMapper.selectMachineList(snList);
  }

  @Override
  public int sync(String ids) {
    User u = getUser();
    List<Software> softwares = this.softwareMapper.selectSoftwareByIds(Convert.toStrArray(ids));
    softwares =
        softwares.stream()
            .filter(item -> !"1".equals(item.getSyncStatus()))
            .collect(Collectors.toList());

    String prodAddress = u.getProdAddress();
    if (StringUtils.isEmpty(prodAddress)) {
      throw new RuntimeException("当前未设置正式服务器地址!");
    }
//    String post = HttpUtil.post(u.getProdAddress() + "/lh/software/prodSync", JSON.toJSONString(softwares));
    String post =  JSON.toJSONString(prodSync(JSON.toJSONString(softwares)) > 0? AjaxResult.success() : AjaxResult.error());
    AjaxResult ajaxResult = JSON.parseObject(post, AjaxResult.class);
    if (ajaxResult.isSuccess()) {
      softwares.forEach(
          item -> {
            item.setSyncStatus("0");
            this.updateSoftware(item);
          });
    }
    return softwares.size();
  }

  private User getUser() {
    List<User> users = userService.selectUserList(new User());
    User u;
    if (null == users || users.isEmpty()) {
      u = new User();
    } else {
      u = users.get(0);
    }
    return u;
  }

  @Override
  public int prodSync(String requestStr) {
    List<Software> softwares = JSON.parseArray(requestStr, Software.class);
    softwares.forEach(
        item -> {
          item.setSyncStatus("0");
          item.setTestId(item.getId());
          this.insertSoftware(item);
        });

    User user = getUser();
    TimerTask timerTask =
        new TimerTask() {
          @Override
          public void run() {
            softwares.forEach(
                item -> {
                  System.out.println("item -> " + item.toString());
                  // 本地资源路径
                  // 本地资源路径
                  String localPath = RuoYiConfig.getProfile();
                  // 数据库资源地址
                  String downloadPath =
                      localPath
                          + StringUtils.substringAfter(
                              item.getUpdateFile(), Constants.RESOURCE_PREFIX);
                  File file = new File(downloadPath);
                  HttpUtil.downloadFile(
                      user.getTestAddress() + "/lh/software/download/" + item.getId(), file);
                  // 更新测试环境状态和正式环境状态
                  item.setSyncStatus("1");
                  updateSoftware(item);
                  JSONObject jsonObject = new JSONObject();
                  jsonObject.put("id", item.getTestId());
                  jsonObject.put("syncStatus", "1");
                  jsonObject.put("prodId", item.getId());
                  String post =
                      HttpUtil.post(
                          user.getTestAddress() + "/lh/software/changeStatus",
                          jsonObject.toJSONString());
                  System.out.println("changeStatus" + post);
                });
          }
        };
    // 上传文件
    AsyncManager.me().execute(timerTask);

    return softwares.size();
  }

  @Override
  public int back(String id) {
      User u = getUser();
      Software software = softwareMapper.selectSoftwareById(Long.valueOf(id));
      int i;
      try {
          long testId = software.getTestId();
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("id", software.getTestId());
          jsonObject.put("syncStatus", "2");
          jsonObject.put("prodId", testId);
          String post =
                  HttpUtil.post(
                          u.getTestAddress() + "/lh/software/changeStatus",
                          jsonObject.toJSONString());
          i = softwareMapper.deleteSoftwareById(Long.valueOf(id));
      } catch (Exception e) {
          throw new RuntimeException("当前无需回退");
      }
      return i;
  }

}
